package com.stockz.equity.charting.event.listener;

import java.awt.Dimension;
import java.awt.Rectangle;

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.stockz.equity.charting.event.SetStockChartViewPortEvent;
import com.stockz.equity.charting.view.StockChart;

@Component
public class SetStockChartViewPortEventListener implements
		ApplicationListener<SetStockChartViewPortEvent> {

	@Override
	public void onApplicationEvent(SetStockChartViewPortEvent event) {
		if(event.getSource() instanceof StockChart){
			StockChart stockChart = (StockChart)event.getSource();
			
			Dimension dimension = stockChart.getStockChartPanel().getSize();
			if(dimension == null || (dimension.width == 0 && dimension.height == 0)){
				dimension = stockChart.getStockChartPanel().getPreferredSize();
			}
			
			Rectangle visibleRectangle = stockChart.getStockChartPanel().getVisibleRect();
			
			int x = stockChart.getStockChartPanel().getLocation().x 
			+ dimension.width - visibleRectangle.width;
			
			
			Rectangle rectangle = new Rectangle(
				x,
				stockChart.getStockChartPanel().getLocation().y,
				visibleRectangle.width,
				visibleRectangle.height);
			
		
			stockChart.getViewport().scrollRectToVisible(rectangle);
		}
	}

}
